"""配置窗口模块"""
from PyQt6.QtWidgets import (QMainWindow, QWidget, QVBoxLayout,
                            QLabel, QLineEdit, QTextEdit, QPushButton, QMessageBox,
                            QHBoxLayout, QGroupBox)
from PyQt6.QtCore import pyqtSignal

from chatai.utils.config import ConfigManager

class ConfigWindow(QMainWindow):
    """配置窗口类"""
    
    # 定义信号
    config_saved = pyqtSignal(dict)
    program_started = pyqtSignal()
    program_stopped = pyqtSignal()
    
    def __init__(self):
        """初始化配置窗口"""
        super().__init__()
        self.config_manager = ConfigManager()
        self.init_ui()
        self.load_config()
        
    def init_ui(self):
        """初始化UI"""
        self.setWindowTitle('配置编辑器')
        self.setGeometry(100, 100, 800, 600)
        self.setup_style()
        self.setup_layout()
        
    def setup_style(self):
        """设置样式"""
        self.setStyleSheet("""
            QMainWindow {
                background-color: #f5f5f5;
            }
            QGroupBox {
                border: 2px solid #ddd;
                border-radius: 8px;
                margin-top: 1em;
                font-weight: bold;
            }
            QGroupBox::title {
                subcontrol-origin: margin;
                left: 10px;
                padding: 0 5px;
            }
            QLabel {
                font-size: 14px;
                color: #333;
                font-weight: bold;
            }
            QLineEdit, QTextEdit {
                border: 2px solid #ddd;
                border-radius: 4px;
                padding: 5px;
                background-color: white;
                font-size: 13px;
            }
            QLineEdit:focus, QTextEdit:focus {
                border-color: #4a9eff;
            }
            QPushButton {
                background-color: #4a9eff;
                color: white;
                border: none;
                border-radius: 4px;
                padding: 8px 20px;
                font-size: 14px;
                font-weight: bold;
            }
            QPushButton:hover {
                background-color: #357abd;
            }
            QPushButton:pressed {
                background-color: #2d6da3;
            }
        """)
        
    def setup_layout(self):
        """设置布局"""
        central_widget = QWidget()
        self.setCentralWidget(central_widget)
        layout = QVBoxLayout(central_widget)
        layout.setContentsMargins(20, 20, 20, 20)
        layout.setSpacing(15)

        # API设置组
        layout.addWidget(self.create_api_group())
        
        # 系统设置组
        layout.addWidget(self.create_system_group())
        
        # 监听设置组
        layout.addWidget(self.create_listen_group())
        
        # 按钮布局
        layout.addLayout(self.create_button_layout())
        
    def create_api_group(self):
        """创建API设置组"""
        api_group = QGroupBox('API 设置')
        api_layout = QVBoxLayout()
        api_layout.setSpacing(8)
        
        api_label = QLabel('API Key:')
        self.api_key_input = QLineEdit()
        self.api_key_input.setPlaceholderText('请输入您的API密钥')
        api_layout.addWidget(api_label)
        api_layout.addWidget(self.api_key_input)
        api_group.setLayout(api_layout)
        
        return api_group
        
    def create_system_group(self):
        """创建系统设置组"""
        system_group = QGroupBox('系统设置')
        system_layout = QVBoxLayout()
        system_layout.setSpacing(8)
        
        prompt_label = QLabel('System Prompt:')
        self.system_prompt_input = QTextEdit()
        self.system_prompt_input.setMinimumHeight(100)
        self.system_prompt_input.setPlaceholderText('请输入系统提示词')
        system_layout.addWidget(prompt_label)
        system_layout.addWidget(self.system_prompt_input)
        system_group.setLayout(system_layout)
        
        return system_group
        
    def create_listen_group(self):
        """创建监听设置组"""
        listen_group = QGroupBox('监听设置')
        listen_layout = QVBoxLayout()
        listen_layout.setSpacing(8)
        
        listen_label = QLabel('Listen List (每行一个名字):')
        self.listen_list_input = QTextEdit()
        self.listen_list_input.setMinimumHeight(100)
        self.listen_list_input.setPlaceholderText('请输入需要监听的名字列表\n每行输入一个名字')
        listen_layout.addWidget(listen_label)
        listen_layout.addWidget(self.listen_list_input)
        
        wait_label = QLabel('Merge Wait Time (秒):')
        self.merge_wait_time_input = QLineEdit()
        self.merge_wait_time_input.setPlaceholderText('请输入合并等待时间')
        listen_layout.addWidget(wait_label)
        listen_layout.addWidget(self.merge_wait_time_input)
        listen_group.setLayout(listen_layout)
        
        return listen_group
        
    def create_button_layout(self):
        """创建按钮布局"""
        button_layout = QHBoxLayout()
        button_layout.setContentsMargins(0, 10, 0, 0)
        button_layout.setSpacing(15)
        
        # 保存按钮
        save_button = QPushButton('保存配置')
        save_button.setMinimumWidth(120)
        save_button.clicked.connect(self.save_config)
        button_layout.addWidget(save_button)
        
        # 运行按钮
        self.run_button = QPushButton('运行程序')
        self.run_button.setMinimumWidth(120)
        self.run_button.clicked.connect(self.toggle_program)
        button_layout.addWidget(self.run_button)
        
        # 添加弹性空间，使按钮居中
        button_layout.addStretch(1)
        button_layout.insertStretch(0, 1)
        
        return button_layout
        
    def load_config(self):
        """加载配置"""
        try:
            config = self.config_manager.load_config()
            self.api_key_input.setText(config.get('api_key', ''))
            self.system_prompt_input.setText(config.get('system_prompt', ''))
            self.listen_list_input.setText('\n'.join(config.get('listen_list', [])))
            self.merge_wait_time_input.setText(str(config.get('merge_wait_time', 2.0)))
        except Exception as e:
            QMessageBox.warning(self, '错误', str(e))

    def get_config(self):
        """获取当前配置
        
        Returns:
            dict: 配置字典
        """
        try:
            return {
                'api_key': self.api_key_input.text(),
                'system_prompt': self.system_prompt_input.toPlainText(),
                'listen_list': [name.strip() for name in self.listen_list_input.toPlainText().split('\n') if name.strip()],
                'merge_wait_time': float(self.merge_wait_time_input.text() or '2.0')
            }
        except Exception as e:
            QMessageBox.warning(self, '错误', str(e))
            return None

    def save_config(self):
        """保存配置"""
        try:
            config = self.get_config()
            if config is None:
                return None
                
            self.config_manager.save_config(config)
            QMessageBox.information(self, '成功', '配置已保存')
            self.config_saved.emit(config)
            return config
        except Exception as e:
            QMessageBox.warning(self, '错误', str(e))
            return None

    def toggle_program(self):
        """切换程序运行状态"""
        if self.run_button.text() == '运行程序':
            self.run_program()
        else:
            self.stop_program()

    def run_program(self):
        """运行程序"""
        try:
            config = self.save_config()
            if config is None:
                return
                
            self.run_button.setText('结束程序')
            self.program_started.emit()
            
        except Exception as e:
            QMessageBox.warning(self, '错误', f'启动程序失败：{str(e)}')
            self.run_button.setText('运行程序')
    
    def stop_program(self):
        """停止程序"""
        self.run_button.setText('运行程序')
        self.program_stopped.emit()
        QMessageBox.information(self, '成功', '程序已停止') 